from django.http import JsonResponse

from utils import requests_pro
from rest_framework.views import  APIView
from lxml import etree
from utils import orm
orm.orm_standby()
from dal import models

class CommentRequests(APIView):
    def get(self,request):
        message = {}
        try:
            session =requests_pro.session_requests_b()

            page = session.get(url="https://movie.douban.com/review/best/")

            page.encoding = "utf-8"

            page_text =page.text

            tree = etree.HTML(page_text)

            li_list = tree.xpath('//*[@id="content"]/div/div[1]/div[1]/div')

            models.Comment.objects.all().delete()
            for li in li_list:
                src = li.xpath("./div/a/img/@src")[0]
                comment_title = li.xpath("./div/div/h2/a/text()")[0]

                url = li.xpath("./div/div/h2/a/@href")[0]

                user = li.xpath("./div/header/a[2]/text()")[0]
                try:
                    time = li.xpath("./div/header/span[2]/text()")[0]
                except:
                    time = li.xpath("./div/header/span/text()")[0]

                text_raw = li.xpath("./div/div/div/div[1]/text()")[0]

                text = text_raw.strip()
                if len(text) == 0:
                    text="这篇影评可能有剧透，无法正常显示"
                models.Comment.objects.create(comment_title=comment_title,src=src,url=url,user=user,time=time,text=text)
            message['code'] = 200
            message['message'] = "更新成功"
            return JsonResponse(message)
        except Exception as e:
            print(e)
            message['code'] = 444
            message['message'] = "更新失败"
            return JsonResponse(message)
